<template>
  <div>
    <!-- 搜索栏 -->
    <el-card>
      <el-form :inline="true" :model="queryForm" class="query-form">
        <el-form-item label="姓名">
          <el-input
            v-model="queryForm.name"
            placeholder="请输入姓名"
            size="small"
          />
        </el-form-item>
        <el-form-item label="电话">
          <el-input
            v-model="queryForm.phone"
            placeholder="请输入电话"
            size="small"
          />
        </el-form-item>
        <!-- <el-form-item label="状态" style="width: 200px">
          <el-select
            v-model="queryForm.status"
            placeholder="请选择状态"
            size="small"
          >
            <el-option label="未联系" value="0" />
            <el-option label="已联系" value="1" />
          </el-select>
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格 -->
    <el-card style="margin-top: 16px">
      <template #header>
        <el-button type="primary" @click="dialogVisible = true">新增</el-button>
      </template>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column type="selection" width="55"></el-table-column>
        <!-- <el-table-column label="序号" width="80" align="center">
          <template #default="scope">
            {{ scope.row.id }}
          </template>
        </el-table-column> -->
        <el-table-column
          type="index"
          label="序号"
          width="60"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="name"
          label="姓名"
          min-width="120"
        ></el-table-column>
        <el-table-column prop="companyName" label="公司名称" min-width="150">
          <template #default="{ row }">
            <el-tag size="small" :type="row.companyName ? 'success' : 'info'">
              {{ row.companyName || "未知公司" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="phone"
          label="电话"
          min-width="150"
        ></el-table-column>
        <el-table-column
          prop="qq"
          label="QQ号"
          min-width="150"
        ></el-table-column>

        <el-table-column
          prop="status"
          label="是否联系"
          min-width="100"
          align="center"
        >
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'warning'">
              {{ row.status === 1 ? "已联系" : "未联系" }}
            </el-tag>
          </template>
        </el-table-column>

        <!--        <el-table-column  prop="createBy" label="接待人员" min-width="100" align="center"></el-table-column>-->
        <!--          />-->
        <el-table-column
          prop="createTime"
          label="录入时间"
          min-width="180"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            {{ row.createTime || "-" }}
          </template>
        </el-table-column>
        <!-- <el-table-column
          prop="updateTime"
          label="更新时间"
          min-width="180"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            {{ row.updateTime || '-' }}
          </template>
        </el-table-column> -->
        <el-table-column
          label="操作"
          min-width="160"
          fixed="right"
          align="center"
        >
          <template #default="{ row }">
            <div class="operation-buttons">
              <el-button
                v-if="row.status !== 1"
                type="success"
                size="small"
                @click="changeStutas(row.id)"
                >立即联系</el-button
              >
              <el-tag v-else size="small" type="success" class="status-tag"
                >已联系</el-tag
              >

              <el-button
                type="danger"
                size="small"
                @click="handleDelete(row.id)"
                >删除</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :current-page="currentPage"
        :page-size="pageSize"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </el-card>

    <!-- 新增对话框 -->
    <el-dialog v-model="dialogVisible" title="新增联系人">
      <el-form
        :model="formData"
        :rules="rules"
        ref="formRef"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item label="QQ号" prop="qq">
          <el-input v-model="formData.qq" placeholder="请输入QQ号" />
        </el-form-item>

        <el-form-item>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAdd">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import request from "@/utils/request";
import { ElMessage, ElMessageBox } from "element-plus";
import { useUserStore } from "@/store/modules/user";

// 使用 type 而不是 interface
type ContactItem = {
  id: number;
  name: string;
  phone: string;
  qq: string;
  visitorId: string;
  companyId: number;
  companyName: string;
  createTime: string;
  updateTime: string;
  createBy: number;
  status: string;
};

const userStore = useUserStore();

// 表格数据使用类型注解
const tableData = ref<ContactItem[]>([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const loading = ref(false);

// 查询表单数据
const queryForm = ref({
  name: "",
  phone: "",
});

// 新增表单数据
const formData = ref({
  visitorId: 1,
  companyId: 2,
  name: "",
  phone: "",
  qq: "",
  createBy: 2,
});

// 对话框显示状态
const dialogVisible = ref(false);

const formRef = ref(null);

// 表单验证规则
const rules = {
  name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  phone: [
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的11位手机号码",
      trigger: "blur",
    },
  ],
  qq: [
    { pattern: /^\d{3,}$/, message: "QQ号不能少于3位数字", trigger: "blur" },
  ],
};

// 自定义验证函数：电话和QQ至少填写一个
const validateContactInfo = (formData) => {
  if (!formData.phone && !formData.qq) {
    ElMessage.error("电话号码和QQ至少填写一个");
    return false;
  }
  return true;
};

// 获取表格数据的方法
const fetchTableData = async () => {
  loading.value = true;
  try {
    const { data } = await request({
      url: "/api/v1/contact/getContactPage",
      method: "post",
      params: {
        page: currentPage.value,
        size: pageSize.value,
        companyId: userStore.user?.deptId,
        name: queryForm.value.name || "",
        phone: queryForm.value.phone || "",
      },
    });

    // 更新数据
    tableData.value = data.records;
    total.value = data.total;
    currentPage.value = data.current;
    pageSize.value = data.size;
  } catch (error) {
    console.error("获取数据失败:", error);
    ElMessage.error("获取数据失败");
  } finally {
    loading.value = false;
  }
};

// 查询按钮
const handleSearch = () => {
  currentPage.value = 1; // 查询时回到第一页
  fetchTableData();
};

// 重置按钮
const resetForm = () => {
  queryForm.value.name = "";
  queryForm.value.phone = "";
  queryForm.value.status = "";
  fetchTableData();
};

// 分页大小变化时
const handleSizeChange = (size) => {
  pageSize.value = size;
  fetchTableData();
};

// 页码变化时
const handlePageChange = (page) => {
  currentPage.value = page;
  fetchTableData();
};

// 删除按钮操作
const handleDelete = (id) => {
  ElMessageBox.confirm("确定要删除这条记录吗？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      const res = await request.delete(`/api/v1/contact/delete/${id}`);
      if (res.code === "200") {
        ElMessage.success("删除成功");
        fetchTableData();
      } else {
        ElMessage.error("删除失败");
      }
    } catch (error) {
      console.error("删除请求出错", error);
    }
  });
};

// 新增按钮
const handleAdd = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();

    // 验证电话和QQ至少填写��个
    if (!validateContactInfo(formData.value)) {
      return;
    }

    const response = await request.post("/api/v1/contact/add", formData.value);
    if (response.code === "200") {
      ElMessage.success("新增成功");
      dialogVisible.value = false;
      // 重置表单
      formRef.value.resetFields();
      fetchTableData();
    } else {
      ElMessage.error("新增失败");
    }
  } catch (error) {
    console.error("新增请求出错", error);
  }
};

// // 编辑按钮
// const handleEdit = (row) => {
//   formData.value = { ...row }; // 将当前行的数据赋值给表单
//   dialogVisible.value = true; // 弹出对话框
// };

// // 更新数据
// const handleUpdate = async () => {
//   console.log(formData.value);
//   try {
//     const response = await request.post(
//       `/api/v1/contact/update`,
//       formData.value
//     );
//     if (response.code === "200") {
//       ElMessage.success("更新成功");
//       dialogVisible.value = false; // 关闭对话框
//       fetchTableData(); // 刷新表格
//     } else {
//       ElMessage.error("更新失败");
//     }
//   } catch (error) {
//     console.error("更新请求出错", error);
//   }
// };

// 修改联系状态
const changeStutas = async (id: number) => {
  ElMessageBox.confirm("确定要将该记录标记为已联系吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "info",
  })
    .then(async () => {
      try {
        const response = await request({
          url: `/api/v1/contact/updateStatus`,
          method: "post",
          params: { id },
        });

        if (response.code === 200) {
          ElMessage.success("已标记为已联系");
          // 确保立即刷新数据
          await fetchTableData(); // 使用 await 确保刷新完成
        } else {
          ElMessage.error(response.msg || "状态更新失败");
        }
      } catch (error) {
        console.error("状态更新失败:", error);
        ElMessage.error("状态更新失败");
      }
    })
    .catch(() => {
      // 取消操作时的处理
      ElMessage.info("已取消操作");
    });
};

// 关闭对话框时重置表单
const handleClose = () => {
  formRef.value?.resetFields();
  dialogVisible.value = false;
};

// 页面挂载后加载数据
onMounted(() => {
  fetchTableData();
});
</script>

<style scoped>
/* 主容器样式 */
.el-card {
  width: 100%;
  margin: 0;
  padding: 0;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

/* 卡片头部样式 */
:deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
  background: #fafafa;
}

/* 表格样式 */
.el-table {
  background-color: #ffffff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  width: 100%;
}

/* 表格单元格样式 */
:deep(.el-table td) {
  padding: 8px 0;
}

/* 表格头部样式 */
:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
  padding: 12px 0;
}

/* 搜索栏样式 */
.query-form {
  margin: 0;
  padding: 20px;
  background-color: #ffffff;
  border-radius: 8px;
}

/* 第二个卡片的间距 */
.el-card + .el-card {
  margin-top: 16px;
}

/* 操作按钮器 */
.operation-buttons {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 12px;
}

/* 状态标签样式 */
.status-tag {
  width: 70px;
  text-align: center;
  height: 24px;
  line-height: 24px;
}

/* 按钮统一宽度 */
.operation-buttons .el-button {
  width: 70px;
  padding: 0;
  margin: 0;
  height: 24px;
  line-height: 24px;
}

/* 分页样式优化 */
:deep(.el-pagination) {
  padding: 15px;
  display: flex;
  justify-content: flex-start;
  background: #fff;
  border-top: 1px solid #ebeef5;
}
</style>
